import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { Theme, Language, DeviceType, NetworkStatus } from '@/types';

// 应用状态接口
interface AppState {
  // 主题设置
  theme: Theme;
  
  // 语言设置
  language: Language;
  
  // 设备信息
  deviceType: DeviceType;
  
  // 网络状态
  networkStatus: NetworkStatus;
  
  // 侧边栏状态
  sidebarOpen: boolean;
  sidebarCollapsed: boolean;
  
  // 模态框状态
  modals: {
    settings: boolean;
    help: boolean;
    feedback: boolean;
    about: boolean;
  };
  
  // 通知状态
  notifications: Array<{
    id: string;
    type: 'info' | 'success' | 'warning' | 'error';
    title: string;
    message: string;
    duration?: number;
    timestamp: number;
  }>;
  
  // 用户偏好
  preferences: {
    resultsPerPage: number;
    enableAnimations: boolean;
    enableSounds: boolean;
    autoSave: boolean;
    compactMode: boolean;
  };
  
  // 应用状态
  isOnline: boolean;
  isLoading: boolean;
  lastActivity: number;
  
  // 错误状态
  globalError: string | null;
}

// 应用动作接口
interface AppActions {
  // 主题控制
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  
  // 语言控制
  setLanguage: (language: Language) => void;
  
  // 设备信息
  setDeviceType: (deviceType: DeviceType) => void;
  
  // 网络状态
  setNetworkStatus: (status: NetworkStatus) => void;
  setOnlineStatus: (isOnline: boolean) => void;
  
  // 侧边栏控制
  toggleSidebar: () => void;
  setSidebarOpen: (open: boolean) => void;
  toggleSidebarCollapse: () => void;
  setSidebarCollapsed: (collapsed: boolean) => void;
  
  // 模态框控制
  openModal: (modal: keyof AppState['modals']) => void;
  closeModal: (modal: keyof AppState['modals']) => void;
  closeAllModals: () => void;
  
  // 通知管理
  addNotification: (notification: Omit<AppState['notifications'][0], 'id' | 'timestamp'>) => void;
  removeNotification: (id: string) => void;
  clearNotifications: () => void;
  
  // 偏好设置
  updatePreferences: (preferences: Partial<AppState['preferences']>) => void;
  
  // 应用状态
  setLoading: (loading: boolean) => void;
  updateLastActivity: () => void;
  setGlobalError: (error: string | null) => void;
  
  // 工具方法
  reset: () => void;
}

// 初始状态
const initialState: AppState = {
  theme: 'auto',
  language: 'zh-CN',
  deviceType: 'desktop',
  networkStatus: 'online',
  sidebarOpen: true,
  sidebarCollapsed: false,
  modals: {
    settings: false,
    help: false,
    feedback: false,
    about: false,
  },
  notifications: [],
  preferences: {
    resultsPerPage: 20,
    enableAnimations: true,
    enableSounds: false,
    autoSave: true,
    compactMode: false,
  },
  isOnline: true,
  isLoading: false,
  lastActivity: Date.now(),
  globalError: null,
};

// 创建应用状态管理 store
export const useAppStore = create<AppState & AppActions>()(
  devtools(
    persist(
      immer((set, get) => ({
        ...initialState,

        // 主题控制
        setTheme: (theme: Theme) => {
          set((state) => {
            state.theme = theme;
          });
          
          // 应用主题到 DOM
          applyThemeToDOM(theme);
        },

        toggleTheme: () => {
          const currentTheme = get().theme;
          const newTheme = currentTheme === 'light' ? 'dark' : 'light';
          get().setTheme(newTheme);
        },

        // 语言控制
        setLanguage: (language: Language) => {
          set((state) => {
            state.language = language;
          });
          
          // 更新 HTML lang 属性
          if (typeof document !== 'undefined') {
            document.documentElement.lang = language;
          }
        },

        // 设备信息
        setDeviceType: (deviceType: DeviceType) => {
          set((state) => {
            state.deviceType = deviceType;
          });
        },

        // 网络状态
        setNetworkStatus: (status: NetworkStatus) => {
          set((state) => {
            state.networkStatus = status;
            state.isOnline = status === 'online';
          });
        },

        setOnlineStatus: (isOnline: boolean) => {
          set((state) => {
            state.isOnline = isOnline;
            state.networkStatus = isOnline ? 'online' : 'offline';
          });
        },

        // 侧边栏控制
        toggleSidebar: () => {
          set((state) => {
            state.sidebarOpen = !state.sidebarOpen;
          });
        },

        setSidebarOpen: (open: boolean) => {
          set((state) => {
            state.sidebarOpen = open;
          });
        },

        toggleSidebarCollapse: () => {
          set((state) => {
            state.sidebarCollapsed = !state.sidebarCollapsed;
          });
        },

        setSidebarCollapsed: (collapsed: boolean) => {
          set((state) => {
            state.sidebarCollapsed = collapsed;
          });
        },

        // 模态框控制
        openModal: (modal: keyof AppState['modals']) => {
          set((state) => {
            state.modals[modal] = true;
          });
        },

        closeModal: (modal: keyof AppState['modals']) => {
          set((state) => {
            state.modals[modal] = false;
          });
        },

        closeAllModals: () => {
          set((state) => {
            Object.keys(state.modals).forEach(key => {
              state.modals[key as keyof AppState['modals']] = false;
            });
          });
        },

        // 通知管理
        addNotification: (notification) => {
          const id = `notification_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
          
          set((state) => {
            state.notifications.push({
              ...notification,
              id,
              timestamp: Date.now(),
            });
          });

          // 自动移除通知
          if (notification.duration !== 0) {
            const duration = notification.duration || 5000;
            setTimeout(() => {
              get().removeNotification(id);
            }, duration);
          }
        },

        removeNotification: (id: string) => {
          set((state) => {
            state.notifications = state.notifications.filter((n: any) => n.id !== id);
          });
        },

        clearNotifications: () => {
          set((state) => {
            state.notifications = [];
          });
        },

        // 偏好设置
        updatePreferences: (preferences) => {
          set((state) => {
            state.preferences = { ...state.preferences, ...preferences };
          });
        },

        // 应用状态
        setLoading: (loading: boolean) => {
          set((state) => {
            state.isLoading = loading;
          });
        },

        updateLastActivity: () => {
          set((state) => {
            state.lastActivity = Date.now();
          });
        },

        setGlobalError: (error: string | null) => {
          set((state) => {
            state.globalError = error;
          });
        },

        // 重置状态
        reset: () => {
          set(initialState);
        },
      })),
      {
        name: 'app-store',
        partialize: (state) => ({
          theme: state.theme,
          language: state.language,
          sidebarCollapsed: state.sidebarCollapsed,
          preferences: state.preferences,
        }),
      }
    ),
    {
      name: 'app-store',
    }
  )
);

// 应用主题到 DOM
function applyThemeToDOM(theme: Theme) {
  if (typeof document === 'undefined') return;

  const root = document.documentElement;
  
  if (theme === 'auto') {
    // 自动模式：根据系统偏好设置
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    root.classList.toggle('dark', prefersDark);
  } else {
    root.classList.toggle('dark', theme === 'dark');
  }
}

// 选择器 hooks
export const useTheme = () => useAppStore(state => state.theme);
export const useLanguage = () => useAppStore(state => state.language);
export const useDeviceType = () => useAppStore(state => state.deviceType);
export const useNetworkStatus = () => useAppStore(state => state.networkStatus);
export const useSidebarState = () => useAppStore(state => ({
  open: state.sidebarOpen,
  collapsed: state.sidebarCollapsed,
}));
export const useModals = () => useAppStore(state => state.modals);
export const useNotifications = () => useAppStore(state => state.notifications);
export const usePreferences = () => useAppStore(state => state.preferences);
export const useAppStatus = () => useAppStore(state => ({
  isOnline: state.isOnline,
  isLoading: state.isLoading,
  lastActivity: state.lastActivity,
  globalError: state.globalError,
}));

// 动作 hooks
export const useAppActions = () => useAppStore(state => ({
  setTheme: state.setTheme,
  toggleTheme: state.toggleTheme,
  setLanguage: state.setLanguage,
  setDeviceType: state.setDeviceType,
  setNetworkStatus: state.setNetworkStatus,
  setOnlineStatus: state.setOnlineStatus,
  toggleSidebar: state.toggleSidebar,
  setSidebarOpen: state.setSidebarOpen,
  toggleSidebarCollapse: state.toggleSidebarCollapse,
  openModal: state.openModal,
  closeModal: state.closeModal,
  closeAllModals: state.closeAllModals,
  addNotification: state.addNotification,
  removeNotification: state.removeNotification,
  clearNotifications: state.clearNotifications,
  updatePreferences: state.updatePreferences,
  setLoading: state.setLoading,
  updateLastActivity: state.updateLastActivity,
  setGlobalError: state.setGlobalError,
}));

// 初始化应用状态
export function initializeAppStore() {
  const store = useAppStore.getState();
  
  // 应用主题
  applyThemeToDOM(store.theme);
  
  // 设置语言
  if (typeof document !== 'undefined') {
    document.documentElement.lang = store.language;
  }
  
  // 监听网络状态
  if (typeof window !== 'undefined') {
    const updateOnlineStatus = () => {
      store.setOnlineStatus(navigator.onLine);
    };
    
    window.addEventListener('online', updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);
    
    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleThemeChange = () => {
      if (store.theme === 'auto') {
        applyThemeToDOM('auto');
      }
    };
    
    mediaQuery.addEventListener('change', handleThemeChange);
    
    // 监听用户活动
    const updateActivity = () => store.updateLastActivity();
    ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(event => {
      document.addEventListener(event, updateActivity, { passive: true });
    });
  }
}
